<?php

namespace Reezy\OAuth\Driver;


use Reezy\OAuth\OAuthBase;
use Reezy\OAuth\OAuthException;
use Reezy\OAuth\OAuthInfo;

class OAuthQq extends OAuthBase
{
    const BASE_URL = 'https://graph.qq.com';

    public function getAuthUrl(string $redirectUri = null, string $state = null, bool $isSilent = false): string
    {
        return self::buildUrl(self::BASE_URL . '/oauth2.0/authorize', [
            'client_id' => $this->clientId,
            'redirect_uri' => $this->redirectUri,
            'scope' => 'get_user_info',
            'response_type' => 'code',
        ]);
    }

    public function getAccessToken($code): OAuthInfo
    {
        $token = $this->httpGet(self::BASE_URL . '/oauth2.0/token', [
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'redirect_uri' => $this->redirectUri,
            'code' => $code,
            'grant_type' => 'authorization_code',
            'fmt' => 'json'
        ]);

        if (empty($token['access_token'])) {
            throw new OAuthException('The key "access_token" could not be empty.');
        }

        $me = $this->getOpenId($token['access_token']);

        return OAuthInfo::token($token + $me);
    }

    public function getUserInfo(OAuthInfo $token): OAuthInfo
    {
        $token->checkOpenId();

        $info = $this->httpGet(self::BASE_URL . '/user/get_user_info', [
            'access_token' => $token->getAccessToken(),
            'openid' => $token->getOpenId(),
            'oauth_consumer_key' => $this->clientId,
            'fmt' => 'json'
        ]);

        return OAuthInfo::userinfo($info, 'nickname', 'figureurl_qq_2');
    }

    private function getOpenId($token): array
    {
        return $this->httpGet(self::BASE_URL . '/oauth2.0/me', [
            'access_token' => $token,
            'unionid' => '1',
            'fmt' => 'json'
        ]);
    }
}
